<template>
  <div class="authorization-detail">
    <h2>记录类型权限管理</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    <div class="permission-container">
      <div class="record-types-header">
        <h3>记录类型列表</h3>
        <p v-if="uniqueRecordTypes.length === 0" class="empty-state">暂无可用记录类型</p>
      </div>

        <div class="record-types-table" v-if="uniqueRecordTypes.length > 0">
        <div class="table-header">
          <div class="table-col type-col">记录类型</div>
          <div class="table-col actions-col">操作</div>
        </div>
        
        <div v-for="type in uniqueRecordTypes" :key="type" class="table-row">
          <div class="table-col type-col">{{ getRecordTypeName(type) }} ({{ type }})</div>
          <div class="table-col actions-col">
            <el-button type="primary" size="small" @click="handleView(type)">{{ getPermissionStatus(type, 'view') ? '取消授权' : '授权查看' }}</el-button>
            <el-button type="success" size="small" @click="handleUpdate(type)">{{ getPermissionStatus(type, 'update') ? '取消授权' : '授权修改' }}</el-button>
            <el-button type="danger" size="small" @click="handleDelete(type)">{{ getPermissionStatus(type, 'delete') ? '取消授权' : '授权删除' }}</el-button>
          </div>
        </div>
      </div>
      

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElForm, ElFormItem, ElSwitch, ElCollapse, ElCollapseItem, ElButton, ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const authorizationId = ref(route.params.id);
const authorizationInfo = ref(null);
  const recordTypes = ref([]);
const permissionModules = ref([]);
  const loading = ref(true);
const errorMessage = ref('');

const userInfo = ref(null);
const loadingPermissions = ref(false);
const permissionError = ref('');


// 初始化权限数组，每个元素包含类型和权限
const getPermissionStatus = (type, permissionType) => {
  console.log("types:",type)
  const permission = permissions.value[type];
  console.log(`获取权限 - 类型: ${type}, 权限类型: ${permissionType}, 当前值:`, permission, `所有权限:`, permissions.value);
  return permission ? permission[permissionType] : false;
};
  const permissions = ref({});

// 检查用户权限
const checkUserAccess = async () => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser);

        // 确保授权详情加载完成后再获取权限设置
      await fetchAuthorizationDetail();
      fetchPermissionSettings();
    } else {
      errorMessage.value = '未找到用户信息，请先登录';
    }
  } catch (error) {
    errorMessage.value = '加载用户信息失败';
  } finally {
    loading.value = false;
  }
};

// 获取授权详情
const fetchAuthorizationDetail = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/api/authorizations/${authorizationId.value}`);
    // 恢复正确的数据获取路径 (response.data.data)
      authorizationInfo.value = response.data.data || {};
      console.log("rrrrr完整授权详情响应:", response.data);
      console.log("rrrrr授权详情data字段内容:", response.data.data);
    // 合并API返回的模块数据（如果有）
    if (authorizationInfo.value.permissionModules) {
      // 合并API返回的模块数据
      const newModules = authorizationInfo.value.permissionModules;
      permissionModules.value = [...permissionModules.value, ...newModules];
      
    }
  } catch (error) {
    errorMessage.value = '加载授权详情失败';
    console.error('获取授权详情失败:', error);
  }
};

// 获取权限设置
const fetchPermissionSettings = async () => {
  loadingPermissions.value = true;
  permissionError.value = '';

  try {
    // 获取权限设置和记录类型数据
    const token = localStorage.getItem('token');
     // 验证authorizationId是否存在
     if (!authorizationId.value) {
       console.error('authorizationId is missing or invalid:', authorizationId.value);
       permissionError.value = '授权ID无效，无法加载权限设置';
       loadingPermissions.value = false;
       return;
     }
     const requestUrl = `http://localhost:8080/api/authorizations/${authorizationId.value}/permissions`;
     console.log('准备请求权限设置 - authorizationId:', authorizationId.value);
     console.log('准备请求权限设置 - token存在性:', !!token);
     const response = await axios.get(`http://localhost:8080/api/authorizations/${authorizationId.value}/permissions`, {
       headers: {
         'Authorization': `Bearer ${token}`
       }
     });
     console.log("rrrrr:",response.data.data)
    const resultData = response.data || {};
     console.log('API响应完整数据结构:', resultData);
     console.log('API响应状态码:', response.status);
    const { permissions: apiPermissions = {}, recordTypes: apiRecordTypes = [] } = resultData.data || {};
// 新增：打印完整的API权限数据结构和键名
console.log('API返回的完整权限数据:', apiPermissions);
console.log('API权限数据包含的键名:', Object.keys(apiPermissions));
console.log('API返回的原始权限数据结构:', { keys: Object.keys(apiPermissions), values: apiPermissions });
console.log('API返回的记录类型列表:', apiRecordTypes);
    // 更新记录类型
    // 使用API返回的实际权限数据初始化
        // 解析后端返回的逗号分隔权限字符串
        const parsePermission = (permissionStr, type) => {
          return permissionStr && permissionStr.split(',').includes(type);
        };

        apiRecordTypes.forEach(type => {
          // 检查当前类型是否在各权限列表中
          const hasView = parsePermission(apiPermissions.look, type);
          const hasUpdate = parsePermission(apiPermissions.update, type);
          const hasDelete = parsePermission(apiPermissions.delete, type);
          
          permissions.value[type] = {
            view: hasView || false,
            update: hasUpdate || false,
            delete: hasDelete || false
          };
          
          console.log(`初始化权限 - 类型: ${type}, 查看: ${hasView}, 修改: ${hasUpdate}, 删除: ${hasDelete}`);
        });
        recordTypes.value = apiRecordTypes;
        console.log("从权限API获取的recordTypes:", apiRecordTypes);
    // 初始化权限表单
    
  } catch (error) {
    const status = error.response?.status || '未知状态';
     const errorDetails = error.response?.data || {};
     const errorMsg = `加载权限设置失败 (状态码: ${status}): ${errorDetails.message || '未知错误'}`;
    permissionError.value = errorMsg;
    console.error('获取权限设置失败:', error);
  } finally {
    loadingPermissions.value = false;
  }
};




// 计算去重后的记录类型
const uniqueRecordTypes = computed(() => {
  return [...new Set(recordTypes.value)];
});

// 在组件挂载时检查用户访问权限
onMounted(() => {
  checkUserAccess();
});

      // 按钮点击事件处理函数
const handleView = async (type) => {
  console.log('handleView函数被调用，类型:', type);
  if (type instanceof Event) {
    console.error('错误：按钮点击事件错误传递了Event对象而非类型参数');
    ElMessage.error('按钮绑定错误，请检查模板中的事件参数');
    return;
  }
  console.log('当前权限列表:', permissions.value);
  // 查找权限记录，如果不存在则创建新记录
    let permission = permissions.value[type];
    if (!permission) {
      permission = { type, view: false };
      permissions.value[type] = permission;
      console.log('创建新的权限记录:', permission);
    }
  if (permission) {
    permission.view = !permission.view;
    try {
      // 调试信息：检查基本参数
      console.log('发送查看权限请求:', { type, authorizationId: authorizationId.value, look: permission.view });
      
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未找到认证token，请重新登录');
      }
      
      if (!authorizationId.value) {
        throw new Error('authorizationId未定义');
      }
      
      const url = `http://localhost:8080/api/authorizations/${authorizationId.value}/look`;
      console.log('请求URL:', url);
      
      const response = await axios.patch(url, {
        recordType: type,
        look: permission.view,
        targetUserId: authorizationId.value
      }, {
        headers: {
          'Authorization': `Bearer ${token}`
        },
        timeout: 5000 // 设置5秒超时
      });
      
      console.log('请求成功响应:', response);
      ElMessage.success(permission.view ? '已授予查看权限' : '已撤销查看权限');
      fetchPermissionSettings(); // 更新后重新获取权限数据
    } catch (error) {
      // 详细错误信息
      console.error('更新查看权限失败:', {
        message: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        url: error.config?.url
      });
      
      // 根据错误类型显示不同提示
      if (error.message.includes('token')) {
        ElMessage.error('认证失败，请重新登录');
      } else if (error.message.includes('authorizationId')) {
        ElMessage.error('缺少必要参数，请刷新页面重试');
      } else if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查后端服务是否可用');
      } else {
        ElMessage.error(`操作失败: ${error.response?.data?.message || error.message || '未知错误'}`);
      }
      
      permission.view = !permission.view; // 回滚状态
    }
  }
};

const handleUpdate = async (type) => {
  console.log('handleUpdate函数被调用，类型:', type);
  if (type instanceof Event) {
    console.error('错误：按钮点击事件错误传递了Event对象而非类型参数');
    ElMessage.error('按钮绑定错误，请检查模板中的事件参数');
    return;
  }
  console.log('当前权限列表:', permissions.value);
  // 查找权限记录，如果不存在则创建新记录
  let permission = permissions.value[type];
  if (!permission) {
    permission = { type, view: false, update: false, delete: false };
    permissions.value[type] = permission;
    console.log('创建新的权限记录:', permission);
  }
  if (permission) {
    permission.update = !permission.update;
    try {
      // 调试信息：检查基本参数
      console.log('发送修改权限请求:', { type, authorizationId: authorizationId.value, update: permission.update });
      
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未找到认证token，请重新登录');
      }
      
      if (!authorizationId.value) {
        throw new Error('authorizationId未定义');
      }
      
      const url = `http://localhost:8080/api/authorizations/${authorizationId.value}/update`;
      console.log('请求URL:', url);
      
      const response = await axios.patch(url, {
        recordType: type,
        update: permission.update,
        targetUserId: authorizationId.value
      }, {
        headers: {
          'Authorization': `Bearer ${token}`
        },
        timeout: 5000 // 设置5秒超时
      });
      
      console.log('请求成功响应:', response);
      ElMessage.success(permission.update ? '已授予修改权限' : '已撤销修改权限');
      fetchPermissionSettings(); // 更新后重新获取权限数据
    } catch (error) {
      // 详细错误信息
      console.error('更新修改权限失败:', {
        message: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        url: error.config?.url
      });
      
      // 根据错误类型显示不同提示
      if (error.message.includes('token')) {
        ElMessage.error('认证失败，请重新登录');
      } else if (error.message.includes('authorizationId')) {
        ElMessage.error('缺少必要参数，请刷新页面重试');
      } else if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查后端服务是否可用');
      } else {
        ElMessage.error(`操作失败: ${error.response?.data?.message || error.message || '未知错误'}`);
      }
      
      permission.update = !permission.update; // 回滚状态
    }
  }
};

const handleDelete = async (type) => {
  console.log('handleDelete函数被调用，类型:', type);
  if (type instanceof Event) {
    console.error('错误：按钮点击事件错误传递了Event对象而非类型参数');
    ElMessage.error('按钮绑定错误，请检查模板中的事件参数');
    return;
  }
  console.log('当前权限列表:', permissions.value);
  // 查找权限记录，如果不存在则创建新记录
  let permission = permissions.value[type];
  if (!permission) {
    permission = { type, view: false, update: false, delete: false };
    permissions.value[type] = permission;
    console.log('创建新的权限记录:', permission);
  }
  if (permission) {
    permission.delete = !permission.delete;
    try {
      // 调试信息：检查基本参数
      console.log('发送删除权限请求:', { type, authorizationId: authorizationId.value, delete: permission.delete });
      
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未找到认证token，请重新登录');
      }
      
      if (!authorizationId.value) {
        throw new Error('authorizationId未定义');
      }
      
      const url = `http://localhost:8080/api/authorizations/${authorizationId.value}/delete`;
      console.log('请求URL:', url);
      
      const response = await axios.patch(url, {
        recordType: type,
        delete: permission.delete,
        targetUserId: authorizationId.value
      }, {
        headers: {
          'Authorization': `Bearer ${token}`
        },
        timeout: 5000 // 设置5秒超时
      });
      
      console.log('请求成功响应:', response);
      ElMessage.success(permission.delete ? '已授予删除权限' : '已撤销删除权限');
      fetchPermissionSettings(); // 更新后重新获取权限数据
    } catch (error) {
      // 详细错误信息
      console.error('更新删除权限失败:', {
        message: error.message,
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        url: error.config?.url
      });
      
      // 根据错误类型显示不同提示
      if (error.message.includes('token')) {
        ElMessage.error('认证失败，请重新登录');
      } else if (error.message.includes('authorizationId')) {
        ElMessage.error('缺少必要参数，请刷新页面重试');
      } else if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查后端服务是否可用');
      } else {
        ElMessage.error(`操作失败: ${error.response?.data?.message || error.message || '未知错误'}`);
      }
      
      permission.delete = !permission.delete; // 回滚状态
    }
  }
};

// 获取记录类型对应的模块
const getModuleByCode = (code) => {
  return permissionModules.value.find(m => m.code === code);
};
// 获取记录类型的友好名称
const getRecordTypeName = (code) => {
  const module = getModuleByCode(code);
  return module ? module.name : code; // 找不到时显示原始代码
};

</script>

<style scoped>
.authorization-detail {
  max-width: 800px;
  margin: 80px auto 2rem;
  padding: 2rem;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.back-btn {
  display: inline-block;
  margin-bottom: 1rem;
  color: #409eff;
  text-decoration: none;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message,
.no-access {
  color: #d43f3a;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.no-access {
  color: #e6a23c;
  background-color: #fdf6ec;
  border: 1px solid #ffe58f;
}

.error-icon {
  margin-right: 8px;
  font-size: 16px;
}

.permission-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.permission-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.doctor-info {
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 4px;
  line-height: 1.6;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}

.el-collapse {
  margin-top: 1rem;
}

.el-collapse-item__content {
  padding-bottom: 16px !important;
}

.el-form-item {
  margin-bottom: 15px;
}
.record-type-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.record-types-table {
  width: 100%;
  border-collapse: collapse;
  margin: 1rem 0;
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  font-weight: bold;
  padding: 10px 15px;
  border-radius: 4px 4px 0 0;
}

.table-row {
  display: flex;
  padding: 10px 15px;
  border-bottom: 1px solid #e9e9e9;
  align-items: center;
}

.table-row:last-child {
  border-bottom: none;
}

.table-col {
  padding: 8px 0;
}

.type-col {
  flex: 1;
}

.actions-col {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  min-width: 240px;
}
.record-type-code {
  color: #666;
  font-size: 0.8em;
  margin-left: 8px;
}
.permission-item {
  margin-left: 20px;
  margin-bottom: 8px;
}
.module-not-found {
  color: #909399;
  padding: 10px;
  text-align: center;
}
</style>



